package org.nowcoder.leetcode.linkedList;

/**
 * Title  : 61. Rotate List
 * Source : https://leetcode.cn/problems/rotate-list/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-01
 */
public class LeetCode_61 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {
        //统计链表结点数量
        int count = 0;
        ListNode p = head, tail = null;
        while (p != null) {
            count++;
            tail = p;
            p = p.next;
        }
        //边界条件
        if (count == 0 || count == 1) {
            return head;
        }
        //当 k == count 时，链表恢复原来位置
        k = k % count;
        if (k > 0) {
            int i = 0;
            p = head;
            while (p != null) {
                if (i == count - k - 1) {
                    tail.next = head;
                    head = p.next;
                    p.next = null;
                    break;
                }
                i++;
                p = p.next;
            }
        }
        return head;
    }
}
